//
//  SendViewController.m
//  JingzhiForBusiness
//
//  Created by Admin on 2017/8/1.
//  Copyright © 2017年 cuixiaocun. All rights reserved.
//

#import "SendViewController.h"
#import "XMLReader.h"
#import "AFNetworking.h"
#import "SBJSON.h"
#import "NSObject+SBJSON.h"
#import <CommonCrypto/CommonDigest.h>

@interface SendViewController ()
{
    //BaseRequest
    NSString *skey;
    NSString *sid;
    NSString *uin;
    NSString *pass_ticket;
    NSString*DEVICE;
    //cookieValue
    NSMutableString *cookieValue ;

    NSMutableArray *friendArr;
    NSString *selfName;
    NSString *toName;
    NSString *token;
    NSTimer  *timer;
    int timeNum;
    NSString *webwx_data_ticket;
    NSString *mediaId;
}
@end

@implementation SendViewController
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden =YES;
}

- (void)viewDidLoad {
    {
        timeNum=0;
        DEVICE= @"e767002199979185";
        friendArr =[[NSMutableArray alloc]init];
        [super viewDidLoad];
        
        [self.view setBackgroundColor:BGColor];
        if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
        }
        self.view.backgroundColor =BGColor;
        //替代导航栏的imageview
        UIImageView *topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, CXCWidth, 64)];
        topImageView.userInteractionEnabled = YES;
        topImageView.backgroundColor = NavColor;
        [self.view addSubview:topImageView];
        //添加返回按钮
        UIButton *  returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        returnBtn.frame = CGRectMake(0, 20, 44, 44);
        [returnBtn setImage:[UIImage imageNamed:navBackarrow] forState:UIControlStateNormal];
        [returnBtn addTarget:self action:@selector(returnBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [topImageView addSubview:returnBtn];
        //注册标签
        UILabel *navTitle =[[UILabel alloc] initWithFrame:CGRectMake(100*Width, 20, 550*Width, 44)];
        [navTitle setText:@"发消息"];
        [navTitle setTextAlignment:NSTextAlignmentCenter];
        [navTitle setBackgroundColor:[UIColor clearColor]];
        [navTitle setFont:[UIFont boldSystemFontOfSize:18]];
        [navTitle setNumberOfLines:0];
        [navTitle setTextColor:[UIColor whiteColor]];
        [self.view addSubview:navTitle];
        UIButton *  withDrawlsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        withDrawlsBtn.frame = CGRectMake(CXCWidth-60, 20, 44, 44);
        withDrawlsBtn.titleLabel.font =[UIFont boldSystemFontOfSize:15];
        [withDrawlsBtn setTitle:@"授权" forState:UIControlStateNormal];
        [withDrawlsBtn addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
        [topImageView addSubview:withDrawlsBtn];
        
        UIButton *  withDrawlsBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        withDrawlsBtn2.frame = CGRectMake(CXCWidth-120, 20, 44, 44);
        withDrawlsBtn2.titleLabel.font =[UIFont boldSystemFontOfSize:15];
        [withDrawlsBtn2 setTitle:@"发送" forState:UIControlStateNormal];
        [withDrawlsBtn2 addTarget:self action:@selector(begainSende) forControlEvents:UIControlEventTouchUpInside];
        [topImageView addSubview:withDrawlsBtn2];
    }
    UITextView *textView =[[UITextView alloc]initWithFrame:CGRectMake(100*Width, 150*Width, 550*Width, 400*Width)];
    textView.tag =100;
    [self.view addSubview:textView];
    UIButton *oppositeBtn =[[UIButton alloc]init];
    [oppositeBtn setImage:[UIImage imageNamed:@"register_btn_front"] forState:UIControlStateNormal];
    
    oppositeBtn.frame= CGRectMake(130*Width,75*Width,250*Width, 150*Width);
    oppositeBtn.backgroundColor =[UIColor redColor];
    [oppositeBtn addTarget:self action:@selector(oppositeBtn:) forControlEvents:UIControlEventTouchUpInside];

}
- (void)oppositeBtn:(UIButton *)btn
{
}
- (void)begainSende
{
    [timer invalidate];
    timer = nil;
    timeNum =0;

     timer =  [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(function) userInfo:nil repeats:YES];
}
- (void)function
{
    if (timeNum>=friendArr.count) {
        [timer invalidate];
        timer = nil;
        return;
    }else
    {
        [self sendMessage:timeNum];//发消息
        timeNum++;//时间相加
    }
}
-(void)returnBtnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)send
{
    [ProgressHUD show:@"正在授权，请稍等"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",nil];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型

    //你的接口地址
    NSString *url=[NSString stringWithFormat:@"%@", _titleString];
    NSDictionary *parameter = @{};
    [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSError *parseError = nil;
        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
        // 打印 NSDictionary
        NSLog(@"%@", xmlDictionary);
        //如果授权失败@"此微信账号异常"
        if ([[NSString stringWithFormat:@"%@",[[[xmlDictionary  objectForKey:@"error"] objectForKey:@"ret"] objectForKey:@"text"]]isEqualToString:@"1203"]) {
            [ProgressHUD dismiss];
            [MBProgressHUD showError:@"此微信账号异常" ToView:self.view];
            return ;
        }
        //如果成功
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        skey =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"skey"] objectForKey:@"text"];
        sid =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"wxsid"] objectForKey:@"text"];
        uin =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"wxuin"] objectForKey:@"text"];
        pass_ticket =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"pass_ticket"] objectForKey:@"text"];
        NSLog(@"\n======================================\n");
        NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
        NSLog(@"fields = %@",[fields description]);
        NSURL *url = [NSURL URLWithString:_titleString];
        NSLog(@"\n======================================\n");
        //获取cookie方法1
        NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:url];
        for (NSHTTPCookie *cookie in cookies) {
            [cookieDic setObject:cookie.value forKey:cookie.name];
            NSLog(@"%@",cookie);
        }
        cookieValue = [NSMutableString stringWithFormat:@""];
        for (NSString *key in cookieDic) {
            NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
            if([key isEqualToString:@"webwx_data_ticket"])
            {
                webwx_data_ticket =[cookieDic valueForKey:key];
            }
            [cookieValue appendString:appendString];
        }
           NSLog(@"%@",cookieValue);
        [self allocTheInfo];//
        //webwxinit
        NSLog(@"erweima请求成功JSON:%@", dict);
      }
     
     
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               NSLog(@"网络连接失败");
    }];
    
}
- (void)allocTheInfo//webwxinit
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"wx%@.qq.com",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Host"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com/?lang=zh_CN",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Referer"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com",_iswxqqOrIswxqq2] forHTTPHeaderField:@"Origin"];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"ture" forHTTPHeaderField:@"isAjaxRequest"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];//一般的服务器不推荐使用put和delete，所以这里就没有添加

    //创建你得请求url、设置请求头
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    
    NSString *urlString = [NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=%@&pass_ticket=%@",_iswxqqOrIswxqq2,timeString,pass_ticket];
    NSDictionary *parameter =[[NSDictionary alloc]init];
    NSDictionary *dic =@{
                         @"DeviceID":DEVICE,
                         @"Sid":sid,
                         @"Skey":skey,
                         @"Uin":uin,
                         };
    parameter = @{
                  @"BaseRequest":dic
                  };
    
    NSLog(@"%@",urlString);
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:@{} error:nil];
    
    NSString *param=[NSString stringWithFormat:@"%@", [parameter JSONFragment]];
    //把拼接后的字符串转换为data，设置请求体
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"bodyData=%@",param);
    
    //发起请求
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
       
        if (!error) {
            [self webwxstatusnotify];//好友列表

           NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
           selfName = [[dict objectForKey:@"User"] objectForKey:@"UserName"];
           NSLog(@"afor请求成功JSON:%@", [[dict objectForKey:@"User"] objectForKey:@"UserName"]);
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
    
}
//好友列表
- (void)webwxstatusnotify
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型
    //你的接口地址
    NSString *url=[NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact",_iswxqqOrIswxqq2];
    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    
    NSDictionary *parameter =@{
                         @"lang":@"zh_CN",
                         @"pass_ticket":pass_ticket,
                         @"r":timeString,
                         @"seq":@"0",
                         @"skey":skey
                         };
  
    NSLog(@"%@",url);
    NSLog(@"%@",parameter);
    [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *MemberList =[dict objectForKey:@"MemberList"];
        NSLog(@"请求成功JSON:%@", dict);
        NSLog(@"请求成功JSON:%@", [self logDic:dict]);
        NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        NSError *parseError = nil;

        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
        // 打印 NSDictionary
        NSLog(@"%@", xmlDictionary);

        for (NSDictionary *dicMember in MemberList)
        {
         
            if(([[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"UserName"]] rangeOfString:@"@@"].location ==NSNotFound)&&[[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"Sex"] ]isEqualToString:@"0"])//把公众号剔除
             {

             
             }
             else
             {
              [friendArr addObject:[dicMember objectForKey:@"UserName"]];

             }
            //测试李森的微信
            if ([[dicMember objectForKey:@"PYQuanPin"]isEqualToString:@"xianglebantian"]) {
                toName =[dicMember objectForKey:@"UserName"];
                
            }

        }
        NSLog(@"%@",friendArr);
        
        [self upload];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    
    
    
    
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSLog(@"%@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
//发消息
- (void)sendMessage:(int)intArrId
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"wx%@.qq.com",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Host"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com/?lang=zh_CN",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Referer"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com",_iswxqqOrIswxqq2] forHTTPHeaderField:@"Origin"];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"ture" forHTTPHeaderField:@"isAjaxRequest"];
    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];//一般的服务器不推荐使用put和delete，所以这里就没有添加
    //创建你得请求url、设置请求头
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    NSString *urlString = [NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?lang=zh_CN&pass_ticket=%@",_iswxqqOrIswxqq2,pass_ticket];
    NSDictionary *baseRequest =@{
                                 @"DeviceID":DEVICE,
                                 @"Sid":sid,
                                 @"Skey":skey,
                                 @"Uin":uin,
                                 };
    
    NSDate* dat2 = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a2=[dat2 timeIntervalSince1970]*1000;
    NSLog(@"a2==%f",a2);
    NSString* timeString3 = [NSString stringWithFormat:@"%f", a2 ];//转为字符型
    NSRange range = [timeString3 rangeOfString:@"."]; //现获取要截取的字符串位置
    NSString * result = [timeString3 substringToIndex:range.location]; //截取字符串
    int num = (arc4random() % 10000);
    NSString *clientMsgId =[NSString stringWithFormat:@"%@%.4d",result,num];
    UITextView *texV =[self.view viewWithTag:100];
    
    NSDictionary *msg =@{
                         @"ClientMsgId":clientMsgId,
                         @"Content":texV.text,
                         @"FromUserName":selfName,
                         @"LocalID":clientMsgId,
                         @"ToUserName":friendArr[intArrId],
                         @"Type":@"3",
                         };
    NSDictionary *parameter =@{
                               @"BaseRequest":baseRequest,
                               @"Msg":msg,
                               @"Scene":@"0"
                               };
    NSLog(@"%@",urlString);
    NSLog(@"%@",parameter);
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:@{} error:nil];
    NSString *param=[NSString stringWithFormat:@"%@", [parameter JSONFragment]];
    //把拼接后的字符串转换为data，设置请求体
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"bodyData=%@",param);
    
    //发起请求
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            NSLog(@"step1.responseObject=%@",[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding]);
            NSError *parseError = nil;
            NSLog(@"[manager.requestSerializer HTTPRequestHeaders]=%@",[manager.requestSerializer HTTPRequestHeaders]);
            NSLog(@"[parameter==]%@",[SendViewController dictionaryToJson:parameter ]);
            
            NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            NSLog(@"allinfors%@",str);
            NSLog(@"allinforP%@",parameter);
            
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
            // 打印 NSDictionary
            NSLog(@"%@", xmlDictionary);
            [self sendMessageImg:intArrId];
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"afor请求成功JSON:%@", dict);
            
            
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
    
}

//发消息图片
- (void)sendMessageImg:(int)intArrId
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"wx%@.qq.com",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Host"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com/?lang=zh_CN",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Referer"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com",_iswxqqOrIswxqq2] forHTTPHeaderField:@"Origin"];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"ture" forHTTPHeaderField:@"isAjaxRequest"];
    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];//一般的服务器不推荐使用put和delete，所以这里就没有添加
    
    //创建你得请求url、设置请求头
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    NSString *urlString = [NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket=%@",_iswxqqOrIswxqq2,pass_ticket];
    NSDictionary *baseRequest =@{
                                 @"DeviceID":DEVICE,
                                 @"Sid":sid,
                                 @"Skey":skey,
                                 @"Uin":uin,
                                 };
    
    NSDate* dat2 = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a2=[dat2 timeIntervalSince1970]*1000;
    NSLog(@"a2==%f",a2);
    NSString* timeString3 = [NSString stringWithFormat:@"%f", a2 ];//转为字符型
    NSRange range = [timeString3 rangeOfString:@"."]; //现获取要截取的字符串位置
    NSString * result = [timeString3 substringToIndex:range.location]; //截取字符串
    int num = (arc4random() % 10000);
    NSString *clientMsgId =[NSString stringWithFormat:@"%@%.4d",result,num];
    
    NSDictionary *msg =@{
                         @"ClientMsgId":clientMsgId,
                         @"MediaId":mediaId,
                         @"FromUserName":selfName,
                         @"LocalID":clientMsgId,
                         @"ToUserName":friendArr[intArrId],
//                         @"ToUserName":toName,
                         @"Type":@"3",
                         };
   NSDictionary *parameter =@{
                               @"BaseRequest":baseRequest,
                               @"Msg":msg,
                               @"Scene":@"0"
                               };
    NSLog(@"%@",urlString);
    NSLog(@"%@",parameter);
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:@{} error:nil];
    NSString *param=[NSString stringWithFormat:@"%@", [parameter JSONFragment]];
    //把拼接后的字符串转换为data，设置请求体
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"bodyData=%@",param);
    
    //发起请求
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            NSLog(@"step1.responseObject=%@",[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding]);
            NSError *parseError = nil;
            NSLog(@"[manager.requestSerializer HTTPRequestHeaders]=%@",[manager.requestSerializer HTTPRequestHeaders]);
            NSLog(@"[parameter==]%@",[SendViewController dictionaryToJson:parameter ]);
            
            NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            NSLog(@"allinfors%@",str);
            NSLog(@"allinforP%@",parameter);
            
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
            // 打印 NSDictionary
            NSLog(@"%@", xmlDictionary);
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"afor请求成功JSON:%@", dict);
            
            
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
    
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 +(NSData *)returnDataWithDictionary:(NSDictionary*)dict
 {
         NSMutableData *data = [[NSMutableData alloc]init];
        NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
        [archiver encodeObject:dict forKey:@"talkData"];
      [archiver finishEncoding];
        return data;
     }


- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =[[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                                     withString:@"\\U"];
    NSString *tempStr2 =[tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =[[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =[NSPropertyListSerialization propertyListFromData:tempData
                                                    mutabilityOption:NSPropertyListImmutable
                                                              format:NULL
                                                    errorDescription:NULL];
    return str;
}
- (void)upload
{
        NSString *urlString = [NSString stringWithFormat:@"https://file.wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json",_iswxqqOrIswxqq2];
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
        UIImage *image = [UIImage imageNamed:@"ceshitupian.png"];
        NSData *data = UIImagePNGRepresentation(image);
        NSInteger length = [data length];

    
        NSDictionary *paraData =[[NSDictionary alloc]init];
        NSDictionary *postData =[[NSDictionary alloc]init];
        NSDictionary *dic =@{
                             @"DeviceID":@"e165355858137910",
                             @"Sid":sid,
                             @"Skey":skey,
                             @"Uin":uin,
                             };
        paraData = @{
                     @"BaseRequest":dic,
                     @"UploadType":@2,
                     @"ClientMediaId":timeString,
                     @"TotalLen":[NSString stringWithFormat:@"%ld",length],
                     @"StartPos":@"0",
                     @"DataLen":[NSString stringWithFormat:@"%ld",length],
                     @"MediaType":@4,
//                     @"FromUserName":selfName,
//                     @"ToUserName":toName,
//                     @"FileMd5":[SendViewController getMD5WithData:data],
                     };
    
        postData =@{
                    @"id":@"WU_FILE_0",
                    @"name":@"ceshitupian.png",
                    @"type":@"image/png",
                    @"lastModifiedDate":[self getCurrentTime],
                    @"size":[NSString stringWithFormat:@"%ld",length],
                    @"mediatype":@"pic",
                    @"uploadmediarequest":[paraData JSONFragment],
                    @"webwx_data_ticket":webwx_data_ticket,
                    @"pass_ticket":pass_ticket,
//                    @"filename":encodedImageStr,
                    };
        //根据url初始化request
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
        NSString *url=urlString;
    
        [manager POST:url parameters:postData constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *eachImgData = data;
            //使用日期生成图片名称
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            [formData appendPartWithFileData :eachImgData name : @"filename" fileName : fileName mimeType : @"image/jpg/png/jpeg" ];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"图片请求成功JSON:%@", JSON);
         
            if ([[NSString stringWithFormat:@"%@",[[JSON objectForKey:@"BaseResponse"] objectForKey:@"Ret"]]isEqualToString:@"1"]) {
                NSLog(@"%@",@"参数不对");

            }else if ([[NSString stringWithFormat:@"%@",[[JSON objectForKey:@"BaseResponse"] objectForKey:@"Ret"]]isEqualToString:@"0"]) {
                NSLog(@"%@",@"参数");
                mediaId=[JSON objectForKey:@"MediaId"];
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                       NSLog(@"请求失败:%@", error.description);
        }];
        
    }
+ (NSString*)getMD5WithData:(NSData *)data{
    const char* original_str = (const char *)[data bytes];
    unsigned char digist[CC_MD5_DIGEST_LENGTH]; //CC_MD5_DIGEST_LENGTH = 16
    CC_MD5(original_str, (uint)strlen(original_str), digist);
    NSMutableString* outPutStr = [NSMutableString stringWithCapacity:10];
    for(int  i =0; i<CC_MD5_DIGEST_LENGTH;i++){
        [outPutStr appendFormat:@"%02x",digist[i]];//小写x表示输出的是小写MD5，大写X表示输出的是大写MD5
    }
    return [outPutStr lowercaseString];
    
}
-(int) lBytesToInt:(Byte[]) byte
{
    //    int i;
    //    [[NSData data] getBytes:&i length:sizeof(i)];
    int height = 0;
    NSData * testData =[NSData dataWithBytes:byte length:4];
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte[[testData length]-i] >= 0)
        {
            height = height + byte[[testData length]-i];
        } else
        {
            height = height + 256 + byte[[testData length]-i];
        }
        height = height * 256;
    }
    if (byte[0] >= 0)
    {
        height = height + byte[0];
    } else {
        height = height + 256 + byte[0];
    }
    return height;
}
//获取当地时间
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM dd yyyy HH:mm:ss"];
    NSString *dateTime =[NSString stringWithFormat:@"%@ GMT+0800",[formatter stringFromDate:[NSDate date]]];
    NSLog(@"yyyy MM dd HH:mm:ss%@",dateTime);

    return dateTime;
}
-(NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}



@end
